﻿using System;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Entities;
using CloudShot.Settings;
using CloudShot.Utils;

namespace CloudShot.Forms
{
  public class SaveShotDialog
  {
    private readonly IConfigurationSection _appConfigurationSection;
    private readonly ShotType _shotType;

    public ImageFormat[] ImageFormats { get; set; }

    public string FileName { get; private set; }

    public ImageFormat SelectedImageFormat { get; private set; }

    public SaveShotDialog(IConfigurationSection appConfigurationSection, ShotType shotType)
    {
      _appConfigurationSection = appConfigurationSection;
      _shotType = shotType;
    }

    public DialogResult ShowDialog()
    {
      var settings = _appConfigurationSection.GetOrCreateAs<CloudShotSettings>();

      string dir = string.IsNullOrEmpty(settings.LastSaveFileDir) ? Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) : settings.LastSaveFileDir;

      var formats = ImageFormats ?? new[]
      {
        ImageFormat.Png,
        ImageFormat.Jpeg,
        ImageFormat.Bmp,
        ImageFormat.Gif
      };

      var defaultFormat = formats.First();

      using (var saveFileDialog = new SaveFileDialog())
      {
        saveFileDialog.InitialDirectory = dir;
        saveFileDialog.RestoreDirectory = true;
        saveFileDialog.AddExtension = true;
        saveFileDialog.DefaultExt = defaultFormat.GetExtension();
        saveFileDialog.Filter = ImageFormatUtils.ToSaveFilePattern(formats);
        saveFileDialog.FileName = AppHelper.GenerateShotName(defaultFormat, _shotType);

        DialogResult result = saveFileDialog.ShowDialog();

        if (result != DialogResult.OK)
          return result;

        FileName = saveFileDialog.FileName;

        string fileExtension = Path.GetExtension(FileName);
        SelectedImageFormat = fileExtension.GetImageFormat();

        if (SelectedImageFormat == null)
        {
          SelectedImageFormat = defaultFormat;
          FileName = Path.ChangeExtension(FileName, SelectedImageFormat.GetExtension());
        }

        //renew settings. just in case of multipile access
        settings = _appConfigurationSection.GetOrCreateAs<CloudShotSettings>();
        settings.LastSaveFileDir = Path.GetDirectoryName(saveFileDialog.FileName);
        _appConfigurationSection.SaveAs(settings);

        return result;
      }
    }
  }
}